package com.osmino.contacts.dialer;

import android.content.ContentUris;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.devoteam.quickaction.QuickActionBadge;
import com.osmino.contacts.R;
import com.osmino.contacts.entity.Contact;
import com.osmino.contacts.entity.Phone;
import com.osmino.core.style.IStyleableView;
import com.osmino.core.style.Style;

public class ContactDialerItem extends RelativeLayout implements IStyleableView {

	private final boolean DBG = true;
	private final int LAYOUT = R.layout.contact_dialer_item;
	private static final int PIC_DEF = R.drawable.base_no_avatar_ic;
	private final QuickActionBadge mBadge;
	private final TextView mLabel, mLabelPhone;

	public ContactDialerItem(Context context) {
		super(context);
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(LAYOUT, this);
		mBadge = (QuickActionBadge) findViewById(R.id.contact_item_pic_iv);
		mLabel = (TextView) findViewById(R.id.contact_item_text_tv);
		mLabelPhone = (TextView) findViewById(R.id.contact_item_phone);
	}

	public void clearInfo() {
		mLabel.setText("");
		mBadge.setImageResource(PIC_DEF);
	}

	public void setBackground(boolean isOdd) {
		setBackgroundResource(!isOdd ? R.drawable.base_list_bg_2 : R.drawable.base_list_bg_1);
	}
	
	private int colorGreen = Color.parseColor("#98b933");
	
	public void setInfo(Contact contact, String filterSequence, int phonePosition) {
		clearInfo();
		mLabel.setText(contact.displayName);
		Phone phone = contact.getPhones().get(phonePosition);
		SpannableStringBuilder ssb = new SpannableStringBuilder();
		String number = phone.number.replace("-", "");
		ssb.append(number);
		int startIndex = number.indexOf(filterSequence);
		if (startIndex < 0) {
			startIndex = 0;
		}
		int endIndex = startIndex + filterSequence.length();
		ssb.setSpan(new ForegroundColorSpan(colorGreen), startIndex, endIndex, Editable.SPAN_INCLUSIVE_INCLUSIVE);
		ssb.insert(0, " ");
		ssb.insert(0, phone.label);
		mLabelPhone.setText(ssb);
		if (contact.getPhoto() != null) {
			mBadge.setImageDrawable(new BitmapDrawable(getResources(), contact.getPhoto()));
		} else {
			mBadge.setImageResource(PIC_DEF);
		}
		Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contact.id);
		mBadge.setData((int) contact.id, 1, 1);		
	}

	@Override
	public void setStyle(Style style) {
	}
}